/* eslint-disable no-return-await */
import React, {
  useContext, useState, useEffect, useMemo, Fragment,
} from 'react';
import { observer } from 'mobx-react-lite';
import {
  Form, SelectBox, Password, Select, Tooltip, Icon, Button, DataSet,
} from 'choerodon-ui/pro';
import { useDebounceFn } from 'ahooks';
import Store from './stores';
import UserOptionDataSet from './stores/UserOptionDataSet';
import TwoFormSelectEditor from '../../../../components/twoFormSelectEditor';
import './index.less';
import roleFormDataSet from '@/routes/project-user/list/sider/stores/roleFormDataSet';

export default observer((props) => {
  const {
    prefixCls,
    intlPrefix,
    intl, modal,
    onOk, dsStore, roleAssignDataSet, organizationId, userId, orgRoleDataSet, id,
  } = useContext(Store);
  const [flag, setflag] = useState(true);
  useEffect(() => {
    if (roleAssignDataSet.length === 0) { roleAssignDataSet.create({ memberId: '', roleId: '' }); }
    addDisabled();
  }, [roleAssignDataSet]);
  // eslint-disable-next-line max-len
  const userOptionDataSet = useMemo(() => new DataSet(UserOptionDataSet({ id: organizationId })), [id]);
  function handleCancel() {
    roleAssignDataSet.reset();
  }
  async function handleOk() {
    try {
      roleAssignDataSet.validate();
      if (await roleAssignDataSet.submit()) {
        await roleAssignDataSet.reset();
        await onOk();
        return true;
      }
      return false;
    } catch (err) {
      return false;
    }
  }

  modal.handleCancel(handleCancel);
  modal.handleOk(handleOk);

  const {
    run,
    cancel,
  } = useDebounceFn((str, optionDataSet) => {
    optionDataSet.setQueryParameter('user_name', str);
    if (str !== '') { optionDataSet.query(); }
  }, { wait: 500 });
  //  防抖查询选择框数据
  function handleFilterChange(e, optionDataSet) {
    e.persist();
    run(e.target.value, optionDataSet);
  }
  // 失焦处理
  // function handleBlur(optionDataSet, rowIndex) {
  //   // optionDataSet.reset();
  //   const currentRecord = roleAssignDataSet.current;
  //   const memberIdArr = currentRecord ? currentRecord.get('memberId') || [] : null;
  //   const memberId = memberIdArr && memberIdArr[rowIndex];
  //   if (memberIdArr && !optionDataSet?.some((eachRecord) => eachRecord.get('id') === memberId)) {
  //     memberIdArr[rowIndex] = '';
  //     currentRecord.set('memberId', memberIdArr);
  //   }
  //   // roleAssignDataSet.current.set('memberId', roleAssignDataSet.current.get('textField'));
  // }
  // 失去焦点之后重新查询，重置下拉框列表
  const onBlur = () => {
    run(' ', userOptionDataSet);
  };
  // 渲染选择框数据字段
  function getOption({ record }) {
    const isLdap = record.get('ldap');
    const email = record.get('email');
    const imgUrl = record.get('imageUrl');
    const realName = record.get('realName');
    const loginName = record.get('loginName');
    return (
      <Tooltip placement="left" title={`${email}`}>
        <div className={`${prefixCls}-option`}>
          <div className={`${prefixCls}-option-avatar`}>
            {
              imgUrl ? <img src={imgUrl} alt="userAvatar" style={{ width: '100%' }} />
                : <span className={`${prefixCls}-option-avatar-noavatar`}>{realName && realName.split('')[0]}</span>
            }
          </div>
          <span>{realName}</span>
          <span>
            {`(${loginName})`}
          </span>
        </div>
      </Tooltip>
    );
  }
  // 判断添加按钮是否可见
  const buttonVisibility = () => roleAssignDataSet.records.length > 0;
  // 添加按钮的显示与隐藏
  const addDisabled = () => {
    const formData = roleAssignDataSet.toData();
    if (formData[0].memberId === '' || formData[0].roleId === '') {
      return true;
    }
    if (roleAssignDataSet.current.get('memberId') === '' || roleAssignDataSet.current.get('roleId') === '' || !roleAssignDataSet.current.get('memberId') || !roleAssignDataSet.current.get('roleId')) {
      return true;
    }
    return false;
  };
  // 删除item项
  const handleDeleteItem = (index) => {
    roleAssignDataSet.splice(index, 1);
    // 删除之后需要手动定位current指针，因为可以删除的是当前指针的record项
    roleAssignDataSet.current = roleAssignDataSet.get(roleAssignDataSet.length - 1);
  };
  // 增加item项
  const handleCreatOther = () => {
    roleAssignDataSet.create({ memberId: '', roleId: '' });
  };
  return (
    <div
      className={`${prefixCls} ${prefixCls}-modal`}
    >

      {
        // console.log(roleAssignDataSet.records);
        roleAssignDataSet?.map((item, index) => (
          <Form record={item} columns={13}>
            <Select
              labelLayout="float"
              name="memberId"
              noCache
              searchable
              colSpan={6}
              options={userOptionDataSet}
              onBlur={onBlur()}
              searchMatcher={() => true}
              onInput={(e) => handleFilterChange(e, userOptionDataSet)}
              // onBlur={() => handleBlur(userOptionDataSet, index)}
              onKeyDown={(e) => {
                cancel();
              }}
              style={{ width: '100%' }}
            // eslint-disable-next-line react/jsx-no-bind
              optionRenderer={getOption}
              addonAfter={(
                <Tooltip title="此处需精确输入用户名或登录名来搜索对应的用户">
                  <Icon type="help" className={`${prefixCls}-help-icon`} />
                </Tooltip>
            )}
            />
            <Select
              labelLayout="float"
              name="roleId"
              options={orgRoleDataSet}
              style={{ width: '100%', marginLeft: '5px' }}
              colSpan={5}
            />
            <Button
              colSpan={2}
              style={{
                position: 'relative',
                right: -4,
              }}
              className="two-form-select-editor-button"
              icon="delete_black-o"
              funcType="flat"
              disabled={roleAssignDataSet.records.length <= 1}
              onClick={() => handleDeleteItem(index)}
            />
          </Form>
        )
        )
      }
      {buttonVisibility()
      && (
      <Button
        colSpan={12}
        // color={addDisabled() ? 'gray' : 'blue'}
        onClick={handleCreatOther}
        style={{
          textAlign: 'left',
          marginTop: '-0.04rem',
        }}
        icon="add"
        // disabled={roleAssignDataSet.records.length <= 1}
        disabled={addDisabled()}
      >
        添加其他用户
      </Button>
      )}
    </div>
  );
});
